<template>
  <Dialog
    v-model:model-value="isShowDialog"
    :title="mode === 'edit' ? '编辑任务' : '新增任务'"
    width="600px"
    append-to-body
    destroy-on-close
    @open="handleOpened"
    @close="handleClosed"
  >
    <el-form
      ref="taskEditFormRef"
      :model="form"
      :rules="formRules"
      :label-width="90"
    >
      <el-form-item
        label="任务名称"
        prop="taskName"
        class="common-form-width"
      >
        <el-input
          v-model="form.taskName"
          placeholder="请填写任务名称"
          show-word-limit
          maxlength="20"
        />
      </el-form-item>
      <el-form-item
        label="任务描述"
        prop="taskDescription"
        class="common-form-width"
      >
        <el-input
          v-model="form.taskDescription"
          placeholder="请填写任务描述"
        />
      </el-form-item>
      <el-form-item
        label="任务类型"
        prop="taskType"
        class="common-form-width"
      >
        <el-radio-group
          v-model="form.taskType"
          @change="changeTaskType"
        >
          <el-radio
            v-for="(item, index) in taskTypeList"
            :key="index"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="任务分类"
        prop="categoryIds"
        class="common-form-width"
      >
        <el-select
          v-model="form.categoryIds"
          multiple
          filterable
          allow-create
          :reserve-keyword="false"
          placeholder="请选择任务分类"
        >
          <el-option
            v-for="item in taskCategoryList"
            :key="item.id"
            :label="item.categoryName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <template v-if="form.taskType === 'internal'">
        <el-form-item
          label="跳转链接"
          prop="taskUrl"
          class="common-form-width"
        >
          <el-input
            v-model="form.taskUrl"
            placeholder="请输入跳转链接"
          />
        </el-form-item>
      </template>

      <template v-if="form.taskType === 'external'">
        <el-form-item
          label="对接系统"
          prop="externalMerchantConfigId"
          class="common-form-width"
        >
          <ScSelector
            v-model="form.externalMerchantConfigId"
            type="config"
            :params="{ attach: 'task' }"
          >
            <template #expand-pop="{ data }">
              <div
                v-if="data"
                class="detail-container"
              >
                <div class="detail-text">
                  <h3>
                    {{ data.info.name }}
                  </h3>
                </div>
                <div class="detail-text_line">
                  配置类型：{{ data.info.externalTypeName }}
                </div>
                <div class="detail-text_line">
                  所属平台：{{ data.info.externalPlatformTypeName }}
                </div>
                <div class="detail-text_line">
                  配置标识：{{ data.info.unique }}
                </div>
                <div class="detail-text_line">
                  描述：{{ data.info.remark || "暂无" }}
                </div>
              </div>
            </template>
          </ScSelector>
        </el-form-item>

        <el-form-item
          label="任务编码"
          prop="taskCode"
          class="common-form-width"
        >
          <el-input
            v-model="form.taskCode"
            placeholder="请输入任务编码"
          />
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">
        取消
      </el-button>
      <el-button
        type="primary"
        @click="handleConfirm"
      >
        确定
      </el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import type {FormInstance, FormRules} from "element-plus";
import {useTaskType} from "@/views/taskCenter/compositions/useTaskType";
import {Ref, UnwrapRef, WritableComputedRef} from "vue";
import {ITaskCategoryItem, ITaskEditData, ITaskListItem} from "@/api/modules/taskCenter";
import {getTaskCategory, saveOrUpdateTask} from "@/api/taskCenter";
import {useExternalConfigList} from "@/views/taskCenter/compositions/useExternalConfigList";

const props = defineProps<{
  show: boolean;
  mode: "edit" | "create";
  rowData: ITaskListItem;
}>();
const emits = defineEmits(["update:show", "done"]);
const isShowDialog: WritableComputedRef<boolean> = computed({
  set(newValue) {
    emits("update:show", newValue);
  },
  get() {
    return props.show;
  },
});

const taskEditFormRef = ref<FormInstance>();

const initForm = () => {
  return {
    taskName: "",
    taskDescription: "", // 任务描述
    taskType: "internal", // 任务类型
    taskCode: "",
    categoryIds: [],
    externalMerchantConfigId: null,
    taskUrl: "",
  }
}

const form:UnwrapRef<ITaskEditData> = reactive(initForm());

const formRules = reactive<FormRules>({
  taskName: [{required: true, trigger: "blur", message: "请填写任务名称"}],
  taskDescription: [
    {required: true, trigger: "blur", message: "请填写任务描述"},
  ],
  taskType: [{required: true, trigger: "change", message: "请选择任务类型"}],
  taskCode: [{required: true, trigger: "blur", message: "请填写任务编码"}],
  categoryIds: [
    {
      required: true,
      trigger: "change",
      message: "请选择任务分类",
    },
  ],
  externalMerchantConfigId: [
    {
      required: true,
      trigger: "change",
      message: "请选择对接系统",
    },
  ],
  taskUrl: [
    {
      required: true,
      trigger: "blur",
      message: "请填写任务链接"
    }
  ]
});

const {taskTypeList} = useTaskType();

// 任务分类筛选条件
const taskCategoryList: Ref<ITaskCategoryItem[]> = ref([]);
const _getTaskCategory = async () => {
  const rs = await getTaskCategory({status: 1});
  if (rs.code === 200) {
    taskCategoryList.value = rs.payload ?? [];
  }
};

// 对接系统列表
const {externalConfigList, getExternalConfigList} = useExternalConfigList();

const getTaskInfo = () => {
  // 获取任务信息
  Object.keys(props.rowData).forEach((key) => {
    form[key] = props.rowData[key];
  });
};

const changeTaskType = (val: string) => {
  // 选择内部任务，清空外部任务的表单任务
  if (val === "internal") {
    form.externalMerchantConfigId = null;
    form.taskCode = "";
  } else {
    form.taskUrl = "";
  }
}

const saveLoading = ref(false);
const handleConfirm = async () => {
  // console.log(form)
  taskEditFormRef.value?.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true;
      const rs = await saveOrUpdateTask(form);
      saveLoading.value = false;

      if (rs.code === 200) {
        ElMessage.success("保存成功");
        isShowDialog.value = false;
        emits("done");
      }
    }
  });
};

const handleCancel = () => {
  taskEditFormRef.value?.resetFields()
  isShowDialog.value = false;
};

const handleOpened = () => {
  const initialForm = initForm()
  const initialFormKeys = Object.keys(initialForm)
  initialFormKeys.forEach(key => {
    form[key] = initialForm[key]
  })

  nextTick(() => { // 使resetFields能够生效
    _getTaskCategory();
    getExternalConfigList();

    if (props.mode === "edit") {
      getTaskInfo();
    }
  })
};

const handleClosed = () => {


  taskEditFormRef.value?.resetFields();
};
</script>

<style scoped lang="scss">
@use "@/components/goodsCenter/styles/common.scss";
</style>
